package com.lancoo.znbkxx.teacher.net

import android.util.Base64
import com.lancoo.znbkxx.teacher.utils.ZLibUtils
import okhttp3.Interceptor
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.Response
import okhttp3.ResponseBody
import java.nio.charset.Charset
import java.nio.charset.UnsupportedCharsetException

/**
 * Created by Dadong on 2020/5/19
 * Describe:
 */
class AiInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val response = chain.proceed(request)
        val responseBody = response.body
        var respBody = ""
        if (responseBody != null) {
            val source = responseBody.source()
            source.request(Long.MAX_VALUE)
            val buffer = source.buffer

            var charset = Charset.forName("UTF-8")
            val contentType = responseBody.contentType()
            if (contentType != null) {
                try {
                    charset = contentType.charset(Charset.forName("UTF-8"))
                } catch (e: UnsupportedCharsetException) {
                    e.printStackTrace()
                }
            }
            respBody = buffer.clone().readString(charset)
        }

        try {
            val bytes = Base64.decode(respBody, Base64.DEFAULT)
            val temp = ZLibUtils.decompress(bytes)
            val result = String(temp)
            return response.newBuilder()
                    .body(ResponseBody.create("text/plain".toMediaType(), result)).build()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return response
    }

}